package org.bjou

import org.springframework.dao.DataIntegrityViolationException
import java.util.Locale
import java.text.*
import org.apache.shiro.web.util.SavedRequest
import org.apache.shiro.web.util.WebUtils

class CourseController {
    
    XlsExportService xlsExportService

    static allowedMethods = [save: "POST", update: "POST", delete: "POST",savepick:"POST"]
    
    
   

    def index() {
        redirect(action: "list", params: params)
    }

    def list() {
        
        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
        def round = Config.findByConfigKey('round')?.configValue
        println "currentTerm:"+ currentTerm
        
        if (!params.max) params.max = 20  
        if (!params.offset) params.offset = 0  
        if (!params.sort) params.sort = "id"  
        if (!params.order) params.order = "asc"  
        if (params.currentTerm==null) params.currentTerm = currentTerm
        //params.courseType = "统设"
        
        //params.credit = 5.0
          
        def cel = {  
            if(params.currentTerm){  
                eq("currentTerm", params.currentTerm)
            }
            if(params.entryTerm){  
                eq("entryTerm", params.entryTerm)
            }
            if(params.ruleCode){  
                like("ruleCode", "%${params.ruleCode}%")  
            }
            if(params.majorName){  
                like("majorName", "%${params.majorName}%")  
            }
            if(params.courseId){  
                like("courseId", "%${params.courseId}%")  
            }
            if(params.courseName){  
                like("courseName", "%${params.courseName}%")  
            }
            if(params.courseType){  
                like("courseType", "%${params.courseType}%")  
            }
            if(params.courseProperty){  
                like("courseProperty", "%${params.courseProperty}%")  
            }
            if(params.examType){  
                like("examType", "%${params.examType}%")  
            }
            if(params.departmentName){  
                like("departmentName", "%${params.departmentName}%")  
            }
            if(params.majorLevel){  
                like("majorLevel", "%${params.majorLevel}%")  
            }
            if(params.courseStatus){  
                eq("courseStatus", params.courseStatus)  
            }
            
           
            
            if(params.courseName){  
                like("courseName", "%${params.courseName}%")  
            }
            
            if(params.pickFlag)
            {
              if(params.pickFlag.toString()=="1")
            {
                 sqlRestriction ("id in(select course_id from branch_course where current_term='"+currentTerm+"')"  )
            }
            else
            {
                sqlRestriction ("id not in(select course_id from branch_course where current_term='"+currentTerm+"')"  )
            }  
            }
            
           
        }  
        
        
        
        def courseList = Course.createCriteria().list(params,cel) 
      
        def tocJson=[]
        courseList.each{ ch ->
            def chJson= [:]
            ch.getProperties().each { property ->
                chJson.put property.key, property.value
             }
            chJson["id"] = ch.id
           // 加入两列：责任教师（可能出现不同行有相同教师的情况），
        // 是否选课（已选，未选，只要有一个分校选了就是已选。另外，是否选课也作为查询条件）
        
            
        //def majorLevel = (ch.majorLevel==null)?"无":ch.majorLevel
        
            def credit = chJson["credit"] as double
            chJson["credit"] = credit.round(1)
        
            if(ch.courseStatus=="正开拟不开设")
            {
                 chJson["teacherName"] = "拟不开设"
            }
            else
            {
                def assignInstance = Assign.findByCourseNameAndMajorLevelAndCourseTypeAndCoursePropertyAndExamTypeAndCurrentTermAndRound(ch.courseName,ch.majorLevel,ch.courseType,ch.courseProperty,ch.examType,currentTerm,round)
                if(assignInstance)
                {
                    chJson["teacherName"] = assignInstance.userBaseinfo?.fullname
                }
                else
                {
                    chJson["teacherName"] = ""
                } 
            }
            
            def pickCount = BranchCourse.countByCourseAndCurrentTerm(ch,currentTerm)
            chJson["pickFlag"] = (pickCount>0)?"是":"否"
            
//            if(params.pickFlag)
//            {
//            if((params.pickFlag=="1"&&pickCount>0)||(params.pickFlag=="0"&&pickCount==0))
//            {
//                tocJson << chJson
//            }
//            }
//             else
//             {
//                  tocJson << chJson
//             }
            
            
            tocJson << chJson
            
           
        }
        
        //println tocJson.size()
        
        
        def totalRows = Course.createCriteria().list(cel).size()
        
        
        [courseInstanceList: tocJson, courseInstanceTotal: totalRows]
    }
    
    //发布课程
    def publish() {
        
        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
         
        if (params.currentTerm==null) params.currentTerm = currentTerm
        
        
    }
    
    //发布课程
    def savepublish() {
        
        
        if(params.currentTerm!=null)
        {
            if(params.currentTerm!="")
            {
                //发布：把status改为1
                Course.executeUpdate("update Course b set b.status=1 " +
                      "where b.currentTerm='"+params.currentTerm+"'")
                flash.message = "成功发布了"+params.currentTerm+"的课程"
                redirect(action: "publish")
            }
            else
            {
                flash.message = "请选择学期"
                redirect(action: "publish")
            } 
        }
    }
    
    
    //选课
    def pick() {

        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
        // def deadline = Config.findByConfigKey('branchForecast')?.configValue
        def round = Config.findByConfigKey('round')?.configValue
        
        def strRound = (round=="forecast")?"预报":"正报"
        
        def deadline = (round=="forecast") ? Config.findByConfigKey('branchForecast')?.configValue:Config.findByConfigKey('branchOfficial')?.configValue
        
        def _branch = new Branch()
        //TODO 判断分校角色应该放到Login里面
        if(session.branch)
        {
            _branch = session.branch
        }
        
       
        
        if (!params.max) params.max = 20  
        if (!params.offset) params.offset = 0  
        if (!params.sort) params.sort = "id"  
        if (!params.order) params.order = "asc"  
        if (params.currentTerm==null) params.currentTerm = currentTerm
        if (params.courseStatus==null) params.courseStatus = "正开"



        //params.courseType = "统设"
        
        //params.credit = 5.0
        
          
        def cel = {  
            if(params.currentTerm){  
                eq("currentTerm", params.currentTerm)
            }
            if(params.ruleCode){  
                like("ruleCode", "%${params.ruleCode}%")  
            }
            if(params.majorName){  
                like("majorName", "%${params.majorName}%")  
            }
            if(params.courseId){  
                like("courseId", "%${params.courseId}%")  
            }
            if(params.courseName){  
                like("courseName", "%${params.courseName}%")  
            }
            if(params.courseType){  
                like("courseType", "%${params.courseType}%")  
            }
            if(params.courseProperty){  
                like("courseProperty", "%${params.courseProperty}%")  
            }
            if(params.examType){  
                like("examType", "%${params.examType}%")  
            }
            if(params.departmentName){  
                like("departmentName", "%${params.departmentName}%")  
            }
            if(params.majorLevel){  
                like("majorLevel", "%${params.majorLevel}%")  
            }
            if(params.courseStatus){
                eq("courseStatus", params.courseStatus)
               // like("courseStatus", "%${params.courseStatus}%")
            }
            if(params.courseName){  
                like("courseName", "%${params.courseName}%")  
            }
            //分校只能选择发布的课程
            eq("status", 1)
        }
        
        //需要判断一下正报是否有数据，如果有数据，就应该查正报的数据，如果没有正报的数据，就应该查预报的数据
         def qryRound
        if(round=="official"&&session.branch)
        {
            def bcResult = BranchCourse.findAllByCurrentTermAndBranchAndRound(currentTerm,_branch,round)

            if(bcResult.size()>0)
            {
                qryRound = round
            }
            else
            {
                qryRound = "forecast"
            } 
        }
        else
        {
            qryRound = round
        }
        
        
        
        
        def courseList = Course.createCriteria().list(params,cel) 
        def tocJson=[]
        //def nonPersistent = ["log", "class", "constraints", "properties", "errors", "mapping", "metaClass"]
        courseList.each{ ch ->
            def chJson= [:]
            ch.getProperties().each { property ->
                //if (!nonPersistent.contains(property.key)) 
                // {
                chJson.put property.key, property.value
                // }
            }
            chJson["id"] = ch.id
            //判断是否已经选择了
            if(session.branch)
            {
                def bc = BranchCourse.findByCurrentTermAndBranchAndCourseAndRound(currentTerm,_branch,ch,qryRound)
               // chJson["checked"] = (bc!=null)?"true":"false" 
              
                chJson["pickStatus"] = (bc!=null)?"已选":"未选" 
            }
            else
            {
                chJson["pickStatus"] = "未选" 
               // chJson["checked"] = "false"
            }
          
        
            tocJson << chJson
        }
        
        def totalRows = Course.createCriteria().list(cel).size()
       
        [courseInstanceList: tocJson, courseInstanceTotal: totalRows, deadline:deadline,round:strRound]
    }
    
    
    def savepick() {
        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
       
        println params
        def round = Config.findByConfigKey('round')?.configValue
        
        def deadline = (round=="forecast") ? Config.findByConfigKey('branchForecast')?.configValue:Config.findByConfigKey('branchOfficial')?.configValue
        
        def sdf = new SimpleDateFormat("yyyy-MM-dd")//格式化时间输出  
       
        def currentDate = sdf.format(new Date())
        //println deadline
        //println currentDate
        
        if(currentDate>deadline)
        {
            flash.message="当前已经超过截至日期"
            redirect(action: "pick")
            return
        }
        
        def _branch = new Branch()
        //TODO 判断分校角色应该放到Login里面
        if(session.branch)
        {
            _branch = session.branch
        }
       
        // def _branchlist = Branch.findByUser(_user.id).list(max:1)
       
       
        if(_branch)
        {
            def i=0
            params.list('pickCourse').each {
                def course = Course.findById(it)
                def _branchCourse = new BranchCourse(status:1,currentTerm:currentTerm,round:round)
                
                _branchCourse.setBranch(_branch)
                _branchCourse.setCourse(course)
               
           
                def bc = _branchCourse
                bc = BranchCourse.findByCurrentTermAndBranchAndCourseAndRound(currentTerm,_branch,course,round)
               
                if(bc==null)
                {
                    _branchCourse.save()
                    i++
                }
             
             
           
            }
            flash.message="成功选择了"+i+"门课程，请在选课管理中维护任课老师"
            redirect(action: "pick")
        }
        else
        {
            flash.message="只有分校角色才能完成选课"
            redirect(action: "pick")
        }
        
    }
    
    
    
     def cancelpick() {
        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
        
        
        def round = Config.findByConfigKey('round')?.configValue
        
        def deadline = (round=="forecast") ? Config.findByConfigKey('branchForecast')?.configValue:Config.findByConfigKey('branchOfficial')?.configValue
        
        def sdf = new SimpleDateFormat("yyyy-MM-dd")//格式化时间输出  
       
        def currentDate = sdf.format(new Date())
        //println deadline
        //println currentDate
        
        if(currentDate>deadline)
        {
            flash.message="当前已经超过截至日期"
            redirect(action: "pick")
            return
        }
        
        def _branch = new Branch()
        //TODO 判断分校角色应该放到Login里面
        if(session.branch)
        {
            _branch = session.branch
        }
       
        // def _branchlist = Branch.findByUser(_user.id).list(max:1)
        
        if(_branch)
        {
            // def _branch = _branchlist.get(0)
            def i=0
            params.pickCourse.each {
                def course = Course.findById(it)
                def _branchCourse = new BranchCourse(status:1,currentTerm:currentTerm,round:round)
                
                _branchCourse.setBranch(_branch)
                _branchCourse.setCourse(course)
               
           
                def bc = _branchCourse
                bc = BranchCourse.findByCurrentTermAndBranchAndCourseAndRound(currentTerm,_branch,course,round)
               
                if(bc!=null)
                {
                    _branchCourse.delete()
                    i++
                }
             
             
           
            }
            flash.message="成功取消了"+i+"门课程，请在选课管理中维护任课老师"
            redirect(action: "pick")
        }
        else
        {
            flash.message="只有分校角色才能完成选课"
            redirect(action: "pick")
        }
        
    }
    
    
    //根据页面传入的参数取得job并查询userbaseinfo和job的关系，得到用户列表
    def choose()
    {
        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
        params.majorLevel = (params.majorLevel=="")?null:params.majorLevel
         
        def round = Config.findByConfigKey('round')?.configValue
        
        
        def jobInstance = Job.findByCourseNameAndMajorLevelAndCourseTypeAndCoursePropertyAndExamTypeAndCurrentTermAndRound(params.courseName,params.majorLevel,params.courseType,params.courseProperty,params.examType,currentTerm,round)
        
        
        def cel = {
            sqlRestriction ("id in(select user_baseinfo_jobs_id from user_baseinfo_job where job_id ="+jobInstance?.id+")"  )
        }  
        
        def userBaseinfoList = UserBaseinfo.createCriteria().list(params,cel)
        def totalRows = UserBaseinfo.createCriteria().list(cel).size()
        [userBaseinfoInstanceList: userBaseinfoList, userBaseinfoInstanceTotal: totalRows,jobInstance:jobInstance]
    }
    
    
    //保存选择招聘的信息
    def savechoose() {
        def round = Config.findByConfigKey('round')?.configValue
        params.majorLevel = (params.majorLevel=="")?null:params.majorLevel
         
        
        
        def assignInstance = new Assign(params)
        
        // def assignInstance = Assign.find(paramsAssignInstance)
         
        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
        assignInstance.currentTerm = currentTerm
        assignInstance.round = round
        if(session.department)
        {
            assignInstance.department = session.department
        }
        else
        {
            assignInstance.department = 1
        }
        
        
        def NewAssignInstance = Assign.find(assignInstance)
        
        println "assignInstance"+ assignInstance
        
        if(NewAssignInstance==null)
        {
            NewAssignInstance = assignInstance
        }
        else
        {
            println params.userBaseinfo
            NewAssignInstance.userBaseinfo = UserBaseinfo.get(params.userBaseinfo.id)
        }
        
        println "NewAssignInstance"+ NewAssignInstance
        
             
                 
      
        if (!NewAssignInstance.save(flush: true)) {
            redirect(action: "job")
            return
        }

	flash.message = message(code: 'default.created.message', args: [message(code: 'assign.label', default: 'assign'), assignInstance.courseName])
        

        redirect(action: "job")
    }
    
    
    
    
    
    
    
    
    
    //招聘/分配责任教师
    //20120914 系统发布招聘信息和维护责任教师的时候不是by规则号的，而是by5列distinct之后的列表
    //（5列包括：课程名称，专业层次，考试单位，课程性质，课程类型）。
    //所以该页面列表应该仅显示这5列，在加上课程状态（可考，正开等）。
    def job() {
        
        println params
        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
        if (params.currentTerm==null) params.currentTerm = currentTerm
        
         def round = Config.findByConfigKey('round')?.configValue
        
        if (!params.max) params.max = 20  
        if (!params.offset) params.offset = 0  
        //if (!params.sort) params.sort = "id"  
        //if (!params.order) params.order = "asc"  
        //if (params.entryTerm==null) params.entryTerm = currentTerm
          
        def cel = {
            if(session.department)
            eq("department.id", session.department.id.toLong())
            if(params.currentTerm){  
                eq("currentTerm", params.currentTerm)
            }
            
            
            if(params.courseName){  
                like("courseName", "%${params.courseName}%")  
            }
            if(params.courseType){  
                like("courseType", "%${params.courseType}%")  
            }
            if(params.courseProperty){  
                like("courseProperty", "%${params.courseProperty}%")  
            }
            if(params.examType){  
                like("examType", "%${params.examType}%")  
            }
            if(params.majorLevel){  
                like("majorLevel", "%${params.majorLevel}%")  
            }
           
            
            //20121205  系部只管理正开课的招聘和选择责任教师
             eq("courseStatus", '正开')
            
            projections {
                //distinct(['courseName','courseProperty'])
                 
                distinct(['courseName','majorLevel','courseType','courseProperty','examType']) 
            } 
           
            //系部只显示有分校选的数据
            sqlRestriction ("id in(select course_id from branch_course where current_term='"+currentTerm+"')"  )
            
//            if(params.jobFlag){  
//                //已发布
//            sqlRestriction ("id in(select course_id from branch_course where current_term='"+currentTerm+"')"  )
//            }
            
        }  
        
        def courseList = Course.createCriteria().list(cel) 
        
        def tocJson=[]
        courseList.each{ ch ->
            println ch
            def chJson= [:]
            chJson['courseName'] = ch[0]
            chJson['majorLevel'] = ch[1]==null?"":ch[1]
            chJson['courseType'] = ch[2]
            chJson['courseProperty'] =  ch[3]
            chJson['examType'] =  ch[4]
            
            
            def assignInstance = Assign.findByCourseNameAndMajorLevelAndCourseTypeAndCoursePropertyAndExamTypeAndCurrentTermAndRound(ch[0],chJson['majorLevel'],ch[2],ch[3],ch[4],currentTerm,round)
            if(assignInstance)
            {
                 chJson['teacherName'] =  assignInstance.userBaseinfo.fullname
            }
            else
            {
                 chJson['teacherName'] = ""
            }
            
            
           
            def jobInstance = Job.findByCourseNameAndMajorLevelAndCourseTypeAndCoursePropertyAndExamTypeAndCurrentTerm(ch[0],chJson['majorLevel'],ch[2],ch[3],ch[4],currentTerm)
            if(jobInstance)
            chJson['jobFlag'] = "已发布"
            else
            chJson['jobFlag'] = "未发布"
         
            if(params.jobFlag)
            {
                if((params.jobFlag=="1"&&jobInstance)||(params.jobFlag=="0"&&!jobInstance))
                {
                     tocJson << chJson
                }
             }
            else
            {
                 tocJson << chJson
            }
           
        }
        def totalRows = tocJson.size()
         
       
        
        
        [courseInstanceList: tocJson, courseInstanceTotal: totalRows]
    }
    
    
    //招聘/分配责任教师
    def assign() {
        
        //招聘分配责任教师：录入教师页面：默认应该显示已经选择过的教师
        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
        def round = Config.findByConfigKey('round')?.configValue
        params.majorLevel = (params.majorLevel=="")?null:params.majorLevel
        
        
        def assignInstance = Assign.findByCourseNameAndMajorLevelAndCourseTypeAndCoursePropertyAndExamTypeAndCurrentTermAndRound(params.courseName,params.majorLevel,params.courseType,params.courseProperty,params.examType,currentTerm,round)
        def userBaseinfoInstance
        if(!assignInstance)
        {
            println "new"
            assignInstance = new Assign(params)
        }
        else
        {
            userBaseinfoInstance = assignInstance.userBaseinfo
        }
       
        
        [assignInstance: assignInstance,userBaseinfoInstance:userBaseinfoInstance]
        
    }
    
    
   
    
    
   
    
    //无责任教师课程查询
    def noTeacherList() {
        
        println params
        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
        
        if (!params.max) params.max = 20  
        if (!params.offset) params.offset = 0  
        if (!params.sort) params.sort = "id"  
        if (!params.order) params.order = "asc" 
        
          
        def cel = {
           
             
            if(session.department)
            eq("department.id", session.department.id.toLong())
            if(params.currentTerm){  
                eq("currentTerm", params.currentTerm)
            }
            if(params.courseName){  
                like("courseName", "%${params.courseName}%")  
            }
            if(params.departmentId){  
                eq("department.id", params.departmentId.toLong())  
            }
            sqlRestriction("id in (select course_id from branch_course where current_term='"+currentTerm+"')")     
 
            //只显示没有责任教师
           sqlRestriction ("id NOT IN( SELECT DISTINCT c.id FROM course c   INNER JOIN assign a ON a.course_name = c.course_name AND a.major_level = c.major_level AND a.course_type = c.course_type AND a.course_property = c.course_property AND a.exam_type = c.exam_type AND a.current_term = c.current_term)" )
            // sqlRestriction ("id NOT IN( SELECT DISTINCT c.id FROM course c   INNER JOIN assign a ON a.course_name = c.course_name  AND a.course_type = c.course_type AND a.course_property = c.course_property AND a.exam_type = c.exam_type AND a.current_term = c.current_term)" )
        }  
        
        def courseList = Course.createCriteria().list(params,cel) 
        def totalRows = Course.createCriteria().list(cel).size()
        // def courseList = Course.findAll("from Course where id in(select course.id from BranchCourse)")
   
        
        
        [courseInstanceList: courseList, courseInstanceTotal: totalRows]
    }
    
    
    def exportQueryList()
    {
         def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
        def round = Config.findByConfigKey('round')?.configValue
        def cel = {  
            if(params.currentTerm){  
                eq("currentTerm", params.currentTerm)
            }
            if(params.entryTerm){  
                eq("entryTerm", params.entryTerm)
            }
            if(params.ruleCode){  
                like("ruleCode", "%${params.ruleCode}%")  
            }
            if(params.majorName){  
                like("majorName", "%${params.majorName}%")  
            }
            if(params.courseId){  
                like("courseId", "%${params.courseId}%")  
            }
            if(params.courseName){  
                like("courseName", "%${params.courseName}%")  
            }
            if(params.courseType){  
                like("courseType", "%${params.courseType}%")  
            }
            if(params.courseProperty){  
                like("courseProperty", "%${params.courseProperty}%")  
            }
            if(params.examType){  
                like("examType", "%${params.examType}%")  
            }
            if(params.departmentName){  
                like("departmentName", "%${params.departmentName}%")  
            }
            if(params.majorLevel){  
                like("majorLevel", "%${params.majorLevel}%")  
            }
            if(params.courseStatus){  
                eq("courseStatus", params.courseStatus)  
            }
            
           
            
            if(params.courseName){  
                like("courseName", "%${params.courseName}%")  
            }
        }  
        
        
        
        def courseList = Course.createCriteria().list(params,cel) 
         def tocJson=[]
        courseList.each{ ch ->
            def chJson= [:]
            ch.getProperties().each { property ->
                chJson.put property.key, property.value
             }
            chJson["id"] = ch.id
           // 加入两列：责任教师（可能出现不同行有相同教师的情况），
        // 是否选课（已选，未选，只要有一个分校选了就是已选。另外，是否选课也作为查询条件）
        
            
        //def majorLevel = (ch.majorLevel==null)?"无":ch.majorLevel
        
        
             if(ch.courseStatus=="正开拟不开设")
            {
                 chJson["teacherName"] = "拟不开设"
            }
            else
            {
                def assignInstance = Assign.findByCourseNameAndMajorLevelAndCourseTypeAndCoursePropertyAndExamTypeAndCurrentTermAndRound(ch.courseName,ch.majorLevel,ch.courseType,ch.courseProperty,ch.examType,currentTerm,round)
                if(assignInstance)
                {
                    chJson["teacherName"] = assignInstance.userBaseinfo?.fullname
                }
                else
                {
                    chJson["teacherName"] = ""
                } 
            }
            
            def pickCount = BranchCourse.countByCourseAndCurrentTerm(ch,currentTerm)
            chJson["pickFlag"] = (pickCount>0)?"是":"否"
            
            tocJson << chJson
        }
        
         def sdf = new SimpleDateFormat("yyyyMMddHHmmss")
        XlsExportService xlsExportService = new XlsExportService();  
        response.setHeader("Content-disposition", "attachment; filename="+sdf.format(new Date())+".xls")
        response.setContentType("application/vnd.ms-excel")
        xlsExportService.courseExport(response.outputStream, tocJson)
        
    }
    
    
    //课程查询
    def queryList() {
        
        
         def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
        def round = Config.findByConfigKey('round')?.configValue
        println "currentTerm:"+ currentTerm
        
        if (!params.max) params.max = 20  
        if (!params.offset) params.offset = 0  
        if (!params.sort) params.sort = "id"  
        if (!params.order) params.order = "asc"  
        if (params.currentTerm==null) params.currentTerm = currentTerm
        //params.courseType = "统设"
        
        //params.credit = 5.0
          
        def cel = {  
            if(params.currentTerm){  
                eq("currentTerm", params.currentTerm)
            }
            if(params.entryTerm){  
                eq("entryTerm", params.entryTerm)
            }
            if(params.ruleCode){  
                like("ruleCode", "%${params.ruleCode}%")  
            }
            if(params.majorName){  
                like("majorName", "%${params.majorName}%")  
            }
            if(params.courseId){  
                like("courseId", "%${params.courseId}%")  
            }
            if(params.courseName){  
                like("courseName", "%${params.courseName}%")  
            }
            if(params.courseType){  
                like("courseType", "%${params.courseType}%")  
            }
            if(params.courseProperty){  
                like("courseProperty", "%${params.courseProperty}%")  
            }
            if(params.examType){  
                like("examType", "%${params.examType}%")  
            }
            if(params.departmentName){  
                like("departmentName", "%${params.departmentName}%")  
            }
            if(params.majorLevel){  
                like("majorLevel", "%${params.majorLevel}%")  
            }
            if(params.courseStatus){  
                eq("courseStatus", params.courseStatus)  
            }
            
           
            
            if(params.courseName){  
                like("courseName", "%${params.courseName}%")  
            }
            
            if(params.pickFlag)
            {
              if(params.pickFlag.toString()=="1")
            {
                 sqlRestriction ("id in(select course_id from branch_course where current_term='"+currentTerm+"')"  )
            }
            else
            {
                sqlRestriction ("id not in(select course_id from branch_course where current_term='"+currentTerm+"')"  )
            }  
            }
        }  
        
        
        
        def courseList = Course.createCriteria().list(params,cel) 
      
        def tocJson=[]
        courseList.each{ ch ->
            def chJson= [:]
            ch.getProperties().each { property ->
                chJson.put property.key, property.value
             }
            chJson["id"] = ch.id
           // 加入两列：责任教师（可能出现不同行有相同教师的情况），
        // 是否选课（已选，未选，只要有一个分校选了就是已选。另外，是否选课也作为查询条件）
        
            
        //def majorLevel = (ch.majorLevel==null)?"无":ch.majorLevel
        
             def credit = chJson["credit"] as double
            chJson["credit"] = credit.round(1)
            
            
            if(ch.courseStatus=="正开拟不开设")
            {
                 chJson["teacherName"] = "拟不开设"
            }
            else
            {
                def assignInstance = Assign.findByCourseNameAndMajorLevelAndCourseTypeAndCoursePropertyAndExamTypeAndCurrentTermAndRound(ch.courseName,ch.majorLevel,ch.courseType,ch.courseProperty,ch.examType,currentTerm,round)
                if(assignInstance)
                {
                    chJson["teacherName"] = assignInstance.userBaseinfo?.fullname
                }
                else
                {
                    chJson["teacherName"] = ""
                } 
            }
            
            
            def pickCount = BranchCourse.countByCourseAndCurrentTerm(ch,currentTerm)
            chJson["pickFlag"] = (pickCount>0)?"是":"否"
            
            tocJson << chJson
        }
        
          [courseInstanceList: tocJson, courseInstanceTotal: courseList.totalCount]
    }
    
    
    
    // 资源大表 
    def resourceList() {
        
//        println params
//        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
//        
//        if (!params.max) params.max = 20  
//        if (!params.offset) params.offset = 0  
//        if (!params.sort) params.sort = "id"  
//        if (!params.order) params.order = "asc"  
//          
//        def cel = {
//            if(session.department)
//            eq("department.id", session.department.id.toLong())
//            if(params.currentTerm){  
//                eq("currentTerm", params.currentTerm)
//            }
//            if(params.majorLevel){  
//                eq("majorLevel", params.majorLevel)  
//            }
//            //系部只显示聘任课程信息
//            sqlRestriction ("id in(select course_id from branch_course where current_term='"+currentTerm+"')"  )
//        }  
//        
//        def courseList = Course.createCriteria().list(params,cel) 
//        
//        // def courseList = Course.findAll("from Course where id in(select course.id from BranchCourse)")
//   
//        
//        
//        [courseInstanceList: courseList, courseInstanceTotal: courseList.totalCount]
    }
    
    def exportResourceList()
    {
        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
        def round = Config.findByConfigKey('round')?.configValue
        def cel = {  
           
            if(params.entryTerm){  
                eq("entryTerm", params.entryTerm)
            }
             if(params.majorLevel){  
                like("majorLevel", "%${params.majorLevel}%")  
            }
            
            //所有的正开课程
            //eq("courseStatus","正开")
            
        }  
        
        
        
        def courseList = Course.createCriteria().list(params,cel) 
         def tocJson=[]
        courseList.each{ ch ->
            def chJson= [:]
            ch.getProperties().each { property ->
                chJson.put property.key, property.value
             }
            chJson["id"] = ch.id
            def assignInstance = Assign.findByCourseNameAndMajorLevelAndCourseTypeAndCoursePropertyAndExamTypeAndCurrentTermAndRound(ch.courseName,ch.majorLevel,ch.courseType,ch.courseProperty,ch.examType,currentTerm,round)
            if(assignInstance)
            {
                chJson["teacherName"] = assignInstance.userBaseinfo?.fullname
            }
            else
            {
                chJson["teacherName"] = ""
            }
            
            tocJson << chJson
        }
         
        def sdf = new SimpleDateFormat("yyyyMMddHHmmss")
        XlsExportService xlsExportService = new XlsExportService();  
        response.setHeader("Content-disposition", "attachment; filename="+sdf.format(new Date())+".xls")
        response.setContentType("application/vnd.ms-excel")
        xlsExportService.resourceExport(response.outputStream, tocJson)
    }
    
    
    def saveassign() {
        params.majorLevel = (params.majorLevel=="")?null:params.majorLevel
        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
        
        def round = Config.findByConfigKey('round')?.configValue
        
        
        def assignInstance = Assign.findByCourseNameAndMajorLevelAndCourseTypeAndCoursePropertyAndExamTypeAndCurrentTermAndRound(params.courseName,params.majorLevel,params.courseType,params.courseProperty,params.examType,currentTerm,round)
        
        if(!assignInstance)
        {
            assignInstance = new Assign(params)
            assignInstance.round = round
            assignInstance.currentTerm = currentTerm
        }
        
        //assignInstance.userBaseinfo.id = params.userBaseinfo.id
       
        assignInstance.setUserBaseinfo(UserBaseinfo.get(params.userBaseinfo.id))
        
        if(session.department)
        {
            assignInstance.department = session.department
        }
        else
        {
             assignInstance.department = Department.get(1)
        }
       
                 
      
        if (!assignInstance.save(flush: true)) {
            redirect(action: "job")
            return
        }

	flash.message = message(code: 'default.created.message', args: [message(code: 'assign.label', default: 'assign'), assignInstance.courseName])
        

        redirect(action: "job")
    }

    def create() {
        [courseInstance: new Course(params)]
    }

    def save() {
        def courseInstance = new Course(params)
        if (!courseInstance.save(flush: true)) {
            render(view: "create", model: [courseInstance: courseInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'course.label', default: 'Course'), courseInstance.courseName])
        redirect(action: "show", id: courseInstance.id)
    }

    def show() {
        
        def targetUri 
        // Handle requests saved by Shiro filters.
        //        def savedRequest = WebUtils.getSavedRequest(request)
        //        if (savedRequest) {
        //            targetUri = savedRequest.requestURI - request.contextPath
        //            if (savedRequest.queryString) targetUri = targetUri + '?' + savedRequest.queryString
        //        }
        //        println "targetUri:"+targetUri
        
        
        def courseInstance = Course.get(params.id)
        if (!courseInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'course.label', default: 'Course'), params.id])
            redirect(action: "list")
            return
        }

        [courseInstance: courseInstance]
    }
    
    
    def showReadonly() {
        
        def targetUri 
        // Handle requests saved by Shiro filters.
        //        def savedRequest = WebUtils.getSavedRequest(request)
        //        if (savedRequest) {
        //            targetUri = savedRequest.requestURI - request.contextPath
        //            if (savedRequest.queryString) targetUri = targetUri + '?' + savedRequest.queryString
        //        }
        //        println "targetUri:"+targetUri
        
        
        def courseInstance = Course.get(params.id)
        if (!courseInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'course.label', default: 'Course'), params.id])
            redirect(action: "list")
            return
        }

        [courseInstance: courseInstance]
    }

    def edit() {
        def courseInstance = Course.get(params.id)
        if (!courseInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'course.label', default: 'Course'), params.id])
            redirect(action: "list")
            return
        }

        [courseInstance: courseInstance]
    }

    def update() {
        def courseInstance = Course.get(params.id)
        if (!courseInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'course.label', default: 'Course'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (courseInstance.version > version) {
                courseInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                    [message(code: 'course.label', default: 'Course')] as Object[],
                          "Another user has updated this Course while you were editing")
                render(view: "edit", model: [courseInstance: courseInstance])
                return
            }
        }

        courseInstance.properties = params

        if (!courseInstance.save(flush: true)) {
            render(view: "edit", model: [courseInstance: courseInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'course.label', default: 'Course'), courseInstance.courseName])
        //redirect(action: "show", id: courseInstance.id)
        redirect(action: "list")
    }

    def delete() {
        def courseInstance = Course.get(params.id)
        if (!courseInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'course.label', default: 'Course'), params.id])
            redirect(action: "list")
            return
        }

        try {
            courseInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'course.label', default: 'Course'), params.id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'course.label', default: 'Course'), params.id])
            redirect(action: "show", id: params.id)
        }
    }
    
    
    
    
    
    def upload = { 
        render (view:'upload')
    }
    
     def uploadNew = { 
        render (view:'uploadNew')
    }
    
    
    def uploadCourse = {
        def files = request.getFileMap();
        //handle uploaded file
        def uploadedFile = request.getFile('fileupload')
    
        if(!uploadedFile.empty){
            println "Class: ${uploadedFile.class}"
            println "Name: ${uploadedFile.name}"
            println "OriginalFileName: ${uploadedFile.originalFilename}"
            println "Size: ${uploadedFile.size}"
            println "ContentType: ${uploadedFile.contentType}"

            def webRootDir = servletContext.getRealPath("/")
            def userDir = new File(webRootDir, "/upload")
            userDir.mkdirs()
            uploadedFile.transferTo(new File( userDir, uploadedFile.originalFilename))
            println userDir
      
            println uploadedFile.originalFilename
            def fileName = userDir.toString() + "/" + uploadedFile.originalFilename.toString()
      
      
            ExcelImporter importer = new ExcelImporter(fileName)
      
            def courseList = importer.getCourseList()
            def cList = []
            //Validation
            boolean flag = true
            flash.message = ""
            for(Map courseParams in courseList)
            {
                def newCourse = new Course(courseParams)
                //初始化课程为未发布
                newCourse.status = 0
               
                //根据系部字段维护Department
                
                
                if(newCourse.departmentName!=null)
                {
                   def depart = Department.findByDepartmentName(newCourse.departmentName==null? "":newCourse.departmentName)
                    if(depart)
                    {   
                        newCourse.setDepartment(depart)
                    } 
                }
               //3. 导入课程的时候，系部不作为必填项。根据课程名称查看以往导入记录，
               //找到最近的一次导入记录中的系部作为本次导入的系部。如果找到不止一条记录，则系部字段留空。
                else
                {
                    //先找有几条数据
                    
                    // Course.findByCourseName(newCourse.courseName)
                     
                    def cel={
                        eq("courseName",newCourse.courseName)
                        isNotNull("departmentName")
                        projections {
                            distinct(['departmentName']) 
                        } 
                    }
                  def qryList = Course.createCriteria().list(cel) 
                   println "qryList: " + qryList.size()
                  if(qryList.size()==1)
                  {
                qryList.each{ ch ->
                    println "ch" + ch
                    def depart = Department.findByDepartmentName(ch)
                        if(depart)
                        {   
                            println "true"
                            newCourse.setDepartment(depart)
                            newCourse.setDepartmentName(ch)
                        } 
                    }
                   
                  }
                   
                }
               // 计算入学学期
                // def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
                def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
                newCourse.currentTerm = currentTerm
                //                def _term = new Term("currentTerm":currentTerm,"courseTerm":newCourse.courseTerm)
                //                _term = Term.find(_term)
           
                //newCourse.entryTerm =  calcEntryTerm(currentTerm,newCourse.courseTerm)
               
           
                //根据规则表的内容 
                //总表中的（规则号+学期）匹配适用年度表中的（规则号+推导出的学期），匹配行，标记为“正开课”，否则为非正开课。
                // 其中，针对正开课，需要将适用年度表中的“专业层次”反填回总表
                // 针对非正开课程，查看试卷号和试卷号B
                // 任何一列中有试卷号，则标记为可考课
                //均没有试卷号者，标记为不可考课


              /* if (newCourse.courseStatus!="禁开拟不开设"&&newCourse.courseStatus!="正开拟不开设")
               {
                   newCourse.courseStatus = "可考"
                   def _courseRule = new CourseRule("ruleCode":newCourse.ruleCode,"courseTerm":newCourse.courseTerm)
                   _courseRule = CourseRule.find(_courseRule)

                   if(_courseRule!=null)
                   {
                       newCourse.majorLevel = _courseRule.majorLevel
                       newCourse.courseStatus = "正开"
                       newCourse.courseYear =  _courseRule.ruleYear
                       newCourse.courseSeason =  _courseRule.ruleSeason
                       newCourse.entryTerm =     _courseRule.ruleYear+"年"+ _courseRule.ruleSeason
                   }
               }*/
                def _courseRule = new CourseRule("ruleCode":newCourse.ruleCode,"courseTerm":newCourse.courseTerm)
                _courseRule = CourseRule.find(_courseRule)
                //if 正开
                if(_courseRule!=null)
                {
                    newCourse.majorLevel = _courseRule.majorLevel
                    newCourse.courseStatus = "正开"
                    newCourse.courseYear =  _courseRule.ruleYear
                    newCourse.courseSeason =  _courseRule.ruleSeason
                    // 反填入学季（入学年度&&入学学期）
                    newCourse.entryTerm =     _courseRule.ruleYear+"年"+ _courseRule.ruleSeason
                }
                else
                {
                    def _courseRulekk = new CourseRule("ruleCode":newCourse.ruleCode)
                    _courseRulekk = CourseRule.find(_courseRulekk)
                     if (_courseRulekk!=null)
                     {
                         newCourse.majorLevel = _courseRulekk.majorLevel
                         if (newCourse.courseStatus!="禁开拟不开设"&&newCourse.courseStatus!="正开拟不开设")
                         {
                             newCourse.courseStatus = "可考"
                         }
                        newCourse.courseYear =  _courseRulekk.ruleYear
                         newCourse.courseSeason =  _courseRulekk.ruleSeason
                         //反填入学季（only 规则号匹配，规则制定年度）
                         //TODO 2007秋季->2007年秋季
                         if (!_courseRulekk.ruleSet.contains('年'))
                         newCourse.entryTerm =   _courseRulekk.ruleSet.getAt(0..3)+"年"+  _courseRulekk.ruleSet.getAt(4..5)
                     }

                }




                
                //处理格式
                if(newCourse.examNumber!="NULL" && newCourse.examNumber!="")
                {
                    print newCourse.examNumber
                    try
                    {
                        newCourse.examNumber = newCourse.examNumber.toFloat().toInteger()
                    }
                    catch(Exception e)
                    {
                        newCourse.examNumber = ""
                    }
                       
                }
                if(newCourse.examNumberB!="NULL" && newCourse.examNumberB!="")
                {
                    try
                    {
                        newCourse.examNumberB = newCourse.examNumberB.toFloat().toInteger()
                    }
                    catch(Exception e)
                    {
                        newCourse.examNumberB = ""
                    }
                }
          
                //验证
               
                if(newCourse.courseTerm > 6 )
                {
                    flag = false
                    flash.message += "<p>上传失败, 开课学期列错误，请检查 （规则号为"+ newCourse.ruleCode.toString() + "行）</p>"
                }
//                else if(depart==null)
//                {
//                    flag = false
//                    flash.message += "<p>上传失败, 系部数据列错误，请检查 （规则号为"+ newCourse.ruleCode.toString() + "行）</p>"
//                }
                else
                {
                    cList.add(newCourse)
                }
            }
            //println crList

            if(flag)
            {
                if(cList.size==0)
                {
                    flash.message =  "导入数据为空，请检查文件格式"
                }
                cList.each {c ->
                 
                    if (!c.save()) {
                        flash.message =  "CourseRule not saved, errors = ${c.errors}"
                    }
                    else
                    {
                        flash.message = message(code: 'default.upload.message', args: [message(code: 'course.label', default: 'Course')])
                    }
                }
            }
      
      
          
        }
     
        render (view:'upload')
    }
    
    
    
     def uploadNewCourse = {
        def files = request.getFileMap();
        //handle uploaded file
        def uploadedFile = request.getFile('fileupload')
    
        if(!uploadedFile.empty){
            println "Class: ${uploadedFile.class}"
            println "Name: ${uploadedFile.name}"
            println "OriginalFileName: ${uploadedFile.originalFilename}"
            println "Size: ${uploadedFile.size}"
            println "ContentType: ${uploadedFile.contentType}"

            def webRootDir = servletContext.getRealPath("/")
            def userDir = new File(webRootDir, "/upload")
            userDir.mkdirs()
            uploadedFile.transferTo(new File( userDir, uploadedFile.originalFilename))
            println userDir
      
            println uploadedFile.originalFilename
            def fileName = userDir.toString() + "/" + uploadedFile.originalFilename.toString()
      
      
            ExcelImporter importer = new ExcelImporter(fileName)
      
            def courseList = importer.getCourseNewList()
            def cList = []
            //Validation
            boolean flag = true
            flash.message = ""
            for(Map courseParams in courseList)
            {
                print courseParams
                def newCourse = new Course(courseParams)
                //初始化课程为未发布
                newCourse.status = 0
                
                println newCourse
               
                if(newCourse.departmentName!=null)
                {
                   def depart = Department.findByDepartmentName(newCourse.departmentName==null? "":newCourse.departmentName)
                    if(depart)
                    {   
                        newCourse.setDepartment(depart)
                    } 
                }
               //3. 导入课程的时候，系部不作为必填项。根据课程名称查看以往导入记录，
               //找到最近的一次导入记录中的系部作为本次导入的系部。如果找到不止一条记录，则系部字段留空。
                else
                {
                    
                     
                    def cel={
                        eq("courseName",newCourse.courseName)
                        isNotNull("departmentName")
                        projections {
                            distinct(['departmentName']) 
                        } 
                    }
                  def qryList = Course.createCriteria().list(cel) 
                   println "qryList: " + qryList.size()
                  if(qryList.size()==1)
                  {
                qryList.each{ ch ->
                    println "ch" + ch
                    def depart = Department.findByDepartmentName(ch)
                        if(depart)
                        {   
                            println "true"
                            newCourse.setDepartment(depart)
                            newCourse.setDepartmentName(ch)
                        } 
                    }
                   
                  }
                   
                }
                
               
                
                
                
                
                // 计算入学学期
                // def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
                def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
                newCourse.currentTerm = currentTerm
               // newCourse.entryTerm =  calcEntryTerm(currentTerm,newCourse.courseTerm)
               
     
              /*  //1）如果当前学期是春季，则学期数为1357的是正开课，其他的是不可考
               // 2）如果当前学期是秋季，则学期数为2468的是正开课，其他的都是不可考
               def currentSeason = currentTerm.getAt(5..6)
                if((currentSeason=="春季"&&newCourse.courseTerm%2==1)||(currentSeason=="秋季"&&newCourse.courseTerm%2==0))
                {
                   newCourse.courseStatus = "正开"      
                }
                else
                {
                   newCourse.courseStatus = "不可考"      
                }
                */
              
                
                //处理格式
                if(newCourse.examNumber!="NULL" && newCourse.examNumber!="")
                {
                    try
                    {
                        newCourse.examNumber = newCourse.examNumber.toFloat().toInteger()
                    }
                    catch(Exception e)
                    {
                        newCourse.examNumber = ""
                    }
                       
                }
                if(newCourse.examNumberB!="NULL" && newCourse.examNumberB!="")
                {
                    try
                    {
                        newCourse.examNumberB = newCourse.examNumberB.toFloat().toInteger()
                    }
                    catch(Exception e)
                    {
                        newCourse.examNumberB = ""
                    }
                }
                print newCourse.courseId
          
                //验证
               
                if(newCourse.courseTerm > 8 )
                {
                    flag = false
                    flash.message += "<p>上传失败, 开课学期列错误，请检查 （课程为"+ newCourse.courseName.toString() + "行）</p>"
                }
               
                else
                {
                    cList.add(newCourse)
                }
            }
            //println crList

            if(flag)
            {
                if(cList.size==0)
                {
                    flash.message =  "导入数据为空，请检查文件格式"
                }
                cList.each {c ->
                 
                    //TODO 更新 or 新增
                 
              
                    if (!c.save()) {
                        flash.message =  "CourseRule not saved, errors = ${c.errors}"
                    }
                    else
                    {
                        flash.message = message(code: 'default.upload.message', args: [message(code: 'course.label', default: 'Course')])
                    }
                }
            }
      
      
          
        }
     
        render (view:'uploadNew')
    }
    
    
    //手动刷新
    def refresh()
    {
         def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
         
         def cel = {  
            if(params.currentTerm){  
                eq("currentTerm", params.currentTerm)
            }
         }  
        
        
        
        def courseList = Course.createCriteria().list(params,cel) 
        
          courseList.each{ ch ->
            
             def _courseRule = new CourseRule("ruleCode":ch.ruleCode,"courseTerm":ch.courseTerm)
                _courseRule = CourseRule.find(_courseRule)
          
                if(_courseRule!=null)
                {
                    ch.majorLevel = _courseRule.majorLevel
                    ch.courseStatus = "正开"
                }
                else
                {
                    if(ch.examNumber=="NULL" && ch.examNumberB=="NULL")
                    {
                        ch.courseStatus = "不可考" 
                    }
                    else
                    {
                        ch.courseStatus = "可考"
                    }
                    
                   
                }
                
            ch.save(flush: true)
            
        }
        
        
        
        flash.message =  "数据已刷新"
       redirect(action: "list")
    }
    
    
    
    def calcEntryTerm(currentTerm,courseTerm)
    {
        def currentYear = currentTerm.getAt(0..3).toInteger()
        def currentSeason = currentTerm.getAt(5..6)
        def entrySeason,entryTerm,entryYear
        if((currentSeason=="秋季"&&courseTerm%2!=0)||(currentSeason=="春季"&&courseTerm%2==0))
        {
            entrySeason ="年秋季"
        }
        else
        {
            entrySeason ="年春季"
        }
        
        if(courseTerm%2!=0)
        {
            //奇数
            entryYear = currentYear- (courseTerm-1)/2
            entryTerm = entryYear.toString() << entrySeason
            
        }
        else
        {
            //偶数
            if(currentSeason=="秋季")
            {
                entryYear = currentYear - courseTerm/2 + 1
            }
           else
            {
                 entryYear = currentYear - courseTerm/2 
            }

           
            entryTerm = entryYear.toString() << entrySeason
        }
        return entryTerm
        
        
    }
    
     //取消招聘全部
    def deleteAll()
    {
        def deadline = Config.findByConfigKey('teacherForecast')?.configValue
        def sdf = new SimpleDateFormat("yyyy-MM-dd")//格式化时间输出
        def currentDate = sdf.format(new Date())
        if(currentDate>deadline)
        {
            flash.message="当前已经超过截至日期"
            redirect(controller:"Course",action: "job")
            return
        }
        
        params.list('pickCourse').each
        {
            //println it
            it= it.substring(0, it.length()-1) 
            it= it.substring(1, it.length())
            def arr = it.split(",")
            def k = [:]
            arr.each
            {
                def arr1 = it.split(":")
                arr1[0] = arr1[0].replaceAll(/^\s+/,'')
               k[arr1[0]] = arr1[1]
            }
            def job = new Job(k)
            def jobInstance = Job.find(job)
          
//        if (!jobInstance) {
//            flash.message = message(code: 'default.not.found.message', args: [message(code: 'job.label', default: 'Job'), params.id])
//            return
//        }

        try {
            if(jobInstance)
            {
                jobInstance.delete(flush: true)
            }
            
           
        }
        catch (DataIntegrityViolationException e) {
            flash.message = "此招聘信息已经有人申请，暂时无法删除"
            redirect(controller:"Course",action: "job")
        }

        
        }
        flash.message = "批量取消招聘成功"
        redirect(action: "job")
        
        
    }
    
    //申请招聘全部
    def saveAll()
    {
        // println params
         if(session.department==null)
        {
            flash.message = "只有系部角色才能保存招聘信息"
           redirect(controller:"Course",action: "job")
            return
        }
        
        params.list('pickCourse').each
        {
            //println it
            it= it.substring(0, it.length()-1) 
            it= it.substring(1, it.length())
            def arr = it.split(",")
            def k = [:]
            arr.each
            {
                def arr1 = it.split(":")
                arr1[0] = arr1[0].replaceAll(/^\s+/,'')
               k[arr1[0]] = arr1[1]
            }
            def job = new Job(k)
            def jobInstance = Job.find(job)
            if(!jobInstance)
            {
               jobInstance = job 
            }
            
          
        jobInstance.majorLevel = (jobInstance.majorLevel==null)?"":jobInstance.majorLevel
        
        def round = Config.findByConfigKey('round')?.configValue
       jobInstance.round = round
        def departmentInstance  =  Department.get(session.department.id)
        jobInstance.department = departmentInstance
        
        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
        jobInstance.currentTerm = currentTerm
         println jobInstance
        if (!jobInstance.save(flush: true)) {
            //render(view: "create", model: [jobInstance: jobInstance])
            return
        }

        
        }
        
       //  flash.message = message(code: 'default.created.message', args: [message(code: 'job.label', default: 'Job'), jobInstance.courseName])
      
        flash.message = "批量申请招聘成功"
        redirect(controller:"Course",action: "job")
    }
}
